<template>
	<div>
		<el-dialog
		  title="登录"
		  :visible.sync="loginVisible"
		  width="20%"
		  center
		  :before-close="handleClose">
			  <el-form 
				:model="loginForm" 
				:rules="loginrules" 
				ref="loginForm"  
				:status-icon="true"
				>
				<el-form-item  prop="userName">
				  <el-input v-model="loginForm.userName" placeholder="请输入账号" prefix-icon="el-icon-user-solid"></el-input>
				</el-form-item>
				<el-form-item  prop="password">
				  <el-input v-model="loginForm.password" placeholder="请输入密码" prefix-icon="el-icon-view"></el-input>
				</el-form-item>
				<el-form-item>
				  <el-button type="primary" @click="loginUser('loginForm')" class="fo">注册</el-button>
				</el-form-item>
			  </el-form>
		</el-dialog>
	</div>
</template>

<script>
	import loginApi from "@/api/login.js"
	export default{
		name:"login",
		props:["loginVisible"],
		data(){
			var checkUserName = (rule, value, cb) => {
			  const regUserName = /^[a-zA-Z]\w{5,17}$/;
			  if (regUserName.test(value)) {
			    return cb();
			  }
			  cb(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
			};
			
			var checkPassword = (rule, value, cb) => {
			  const regPassword = /^[a-zA-Z]\w{6,19}$/;
			  if (regPassword.test(value)) {
			    return cb();
			  }
			  cb(new Error("字母开头,长度6-18之间,允许字母数字下划线"));
			};
			return{
				loginForm:{
					userName:"",
					password:"",
				},
				loginrules:{
					userName:[
						{ required: true, message: '请输入用户名', trigger: 'blur' },
						{ validator: checkUserName, message: "字母开头,长度5-16之间,允许字母数字下划线", trigger: "blur" },
					],
					password:[
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ validator: checkPassword, message: "字母开头,长度6-18之间,允许字母数字下划线", trigger: "blur" },
					]
				}
			}
		},
		methods:{
			loginUser(formName){
				this.$refs[formName].validate((valid) => {
				    if (valid) {
				      loginApi.login({userName: this.loginForm.userName, password: this.loginForm.password})
					  .then(res=>{
						  console.log(res.data)
						  if(res.data.code === "001"){
							  this.$notify({
							      message: res.data.msg,
							      type: 'success'
							    });
							  this.$store.commit("setUser",res.data.user)
							  this.handleClose()
							  
							  loginApi.getShoppingCart({user_id: res.data.user.user_id})
							  .then(res=>{
								  if(res.data.code === "001"){
									  this.$store.commit("setCartData",res.data.shoppingCartData)
								  }
							  })
						  }
					  })
				      
					} else {
				      this.$notify({
				          message: res.data.msg,
				          type: 'error'
				        });
				      return false;
				    }
				  });
			},
			handleClose(){
				this.loginForm.userName = ""
				this.loginForm.password = ""
				this.$emit("login")
			}
		}
	}
</script>

<style>
	.fo{
		width: 100%;
	}
</style>
